/**
 * 
 */
package ga.nqueens;

import java.util.List;



/**
 * @author thiago
 *
 */
public class Board {

	private int board[];
	
	/**
	 * @param dimensao
	 */
	public Board(final int dimensao) {
		this.board = new int[dimensao];
		
		for (int i = 0; i < dimensao; i++) {
			addRainha(i, -1);
		}
	}
		
	/**
	 * @param dimensao
	 */
	public Board(List<Integer> pos) {
		
		this(pos.size());
		
		for (int i = 0; i < pos.size(); i++) {
			addRainha(i, pos.get(i));
		}
	}

	public void addRainha(int linha, int coluna) {
		board[linha] = coluna;
	}
	
	public void removeRainha(int linha, int coluna) {
		board[linha] = -1;//add check
	}

	//	 Check if a cell on the board contains a queen
	private boolean cellContainsQueen(int col, int row) {
		
		boolean contains = ( (col < 0) || (row < 0) || (col > (board.length -1)) || (row > (board.length -1)) ) ? false :
			board[row] == col;
		
		return contains;
	}
	
	/**
	 * Number of hits
	 * 
	 * @return
	 */
	public int hits() {
		
		int hits = 0;
		
		for (int i = 0; i < board.length; i++) {
			hits = diagonalHits(i, board[i]);
			
		}
		
		return hits;
	}
	
	public int[] hitsByQueen() {
		
		int hits = 0;
		int[] hitsByQueen = new int[board.length];
		
		for (int i = 0; i < board.length; i++) {
			hits = diagonalHits(i, board[i]);
			hitsByQueen[i] = hits;
		}
		
		return hitsByQueen;
	}
	
	private int diagonalHits(int row, int column) {
		
		int hits = 0;
		
	    for(int r = 1; r < board.length; r++) {
	    	
	    	hits += ((cellContainsQueen(column - r, row - r)) ? 1 : 0) +
	    			((cellContainsQueen(column - r, row + r)) ? 1 : 0) +
	    			((cellContainsQueen(column + r, row - r)) ? 1 : 0) +
	    			((cellContainsQueen(column + r, row + r)) ? 1 : 0);		
	    }
	    
		return hits;
	}
	
}